今天來看 介面與抽象類別 / 泛型 / 擴充
Interface 介面,像是一個SOP或是流程, 大家使用後都一定要照著SOP/流程自己實作一次
var mIronPlayer = ironPlay("Kotlin Android 30天,從 0 到 ML")
mIronPlayer.showTitle()
var mWebinarSpeaker = webinarSpeaker("Kotlin Android 30天,從 0 到 ML 參賽心得")
mWebinarSpeaker.showTitle()
// Interface like SOP or flow
interface TitleInterface{
fun showTitle()
}
class ironPlay(title:String):TitleInterface{
var mTitle = title
override fun showTitle() {
//TODO("Not yet implemented")
println("ironPlay Tilte = $mTitle")
}
}
class webinarSpeaker(title:String):TitleInterface{
var mTitle = title
override fun showTitle() {
//TODO("Not yet implemented")
println("webinarSpeaker Tilte = $mTitle")
}
}
abstract class(抽象類別) 不能直接被實例化,只能被類別繼承。
var mWebSpeaker = webSpeaker("Kotlin Android 30天,從 0 到 ML 辛苦談")
mWebSpeaker.showTitle()
abstract class seminarSpeakers (title:String){
abstract fun showTitle()
}
class webSpeaker(title:String): seminarSpeakers(title) {
var mTitle = title
override fun showTitle() {
//TODO("Not yet implemented")
println("abstract Tilte = $mTitle")
}
}
擴充,不想用繼承或是直接修改類別的話,可以使用擴充,通常用 T 來代表全部物件
var mAnySpeaker = anySpeaker(1234 )
mAnySpeaker.showTitle()
anyEventSpeaker(123456)
anyEventSpeaker("Kotlin Android 30天,從 0 到 ML 談天說地")
println("Extensions Speaker Name = "+mWebSpeaker.getSpeakerName())
//Generic Classes
class anySpeaker<T>(title:T) {
var mTitle = title
fun showTitle() {
//TODO("Not yet implemented")
println("Generic class Tilte = $mTitle")
}
}
//Generic fun
fun <T> anyEventSpeaker(title:T) {
println("Generic fun Tilte = $title")
}
//擴充 Extensions
fun webSpeaker.getSpeakerName() = "Kevin"
執行結果:
https://kotlinlang.org/docs/interfaces.html
https://kotlinlang.org/docs/generics.html#declaration-site-variance